package edu.tyut.game.ui.user.password

import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import edu.tyut.game.R
import edu.tyut.game.databinding.ActivityConfirmPasswordBinding
import edu.tyut.game.logic.model.User
import edu.tyut.game.ui.user.login.LoginActivity
import edu.tyut.game.ui.user.login.LoginViewModel
import edu.tyut.game.utils.LogUtils
import edu.tyut.game.utils.StatusBarUtils

class ConfirmPasswordActivity : AppCompatActivity() {

    private val tag = this::class.simpleName!!

    private lateinit var binding: ActivityConfirmPasswordBinding

    private val viewModel by lazy {
        ViewModelProvider(this)[ConfirmPasswordViewModel::class.java]
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityConfirmPasswordBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 隐藏ActionBar
        // 状态栏透明
        StatusBarUtils.setTranslucentStatusBar(this)

        @Suppress("DEPRECATION")
        // 获得用户
        val user = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra("user", User::class.java)
        }else{
            intent.getParcelableExtra("user")
        }
        LogUtils.d(tag, user.toString())

        // 查看用户密码是否更新
        viewModel.isSuccess.observe(this){
            val isSuccess = it.getOrNull()
            LogUtils.d(tag, "密码修改是否成功： $isSuccess")
            if (isSuccess == true) {
                Toast.makeText(this, "密码修改成功", Toast.LENGTH_LONG).show()
                LoginActivity.actionStart(this)
            }
        }

        binding.confirmModifyButton.setOnClickListener {
            val password = binding.newPassword.text.toString().trim()
            val confirmPassword = binding.confirmPassword.text.toString().trim()
            if (password.isEmpty() or confirmPassword.isEmpty()){
                Toast.makeText(this, "密码不能为空!", Toast.LENGTH_SHORT).show()
            }
            if (password == confirmPassword){
                // 发送请求
                viewModel.user = user!!
                user.password = password
                viewModel.updatePassword(user)
            }

        }
    }
    // 别的Activity启动LoginActivity
    companion object{
        fun actionStart(context: Context, user: User){
            val intent = Intent(context, ConfirmPasswordActivity::class.java)
            intent.putExtra("user", user)
            context.startActivity(intent)
        }
    }
}